package com.tvunetworks.center.user.service.impl;

import com.tvunetworks.center.user.mapper.FeatureMapper;
import com.tvunetworks.center.user.mapper.MenuBarMapper;
import com.tvunetworks.center.user.mapper.MenuMapper;
import com.tvunetworks.center.user.mapper.UserRoleMapper;
import com.tvunetworks.center.user.model.Menu;
import com.tvunetworks.center.user.model.vo.MenuBarVo;
import com.tvunetworks.center.user.model.vo.MenuListVo;
import com.tvunetworks.center.user.service.MenuService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.configurationprocessor.json.JSONArray;
import org.springframework.boot.configurationprocessor.json.JSONException;
import org.springframework.boot.configurationprocessor.json.JSONObject;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * @program: tvucc-user
 * @description: MenuServiceImpl
 * @author lebronchen
 * @create: 2019-03-19 19:03
 **/
@Service
public class MenuServiceImpl implements MenuService {

    private static final Logger LOGGER = LoggerFactory.getLogger(MenuServiceImpl.class);
    @Autowired
    private MenuMapper menuMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private MenuBarMapper menuBarMapper;
    @Autowired
    private FeatureMapper featureMapper;

    @Value("${googleAnalyticsAccount}")
    private String googleAnalyticsAccount;
    //    @Value("${mySource.url}")
//    private String mySourceUrl;
//    @Value("${advanceControl.url}")
//    private String advanceControlUrl;
//    @Value("${tvucc.url}")
//    private String tvuccUrl;
//    @Value("${gridmarket.url}")
//    private String globalGridUrl;
//    @Value("${mediaMind.url}")
//    private String mediaMindUrl;
//    @Value("${ccSwitch.url}")
//    private String ccSwitchUrl;
//    @Value("${supportMenu}")
//    private String supportMenu;
//    @Value("${myReceiver.url}")
//    private String myReceiverUrl;
    @Value("${menuMarkUrl}")
    private String menuMarkUrl;
    @Value("${menuLens}")
    private int menuLens;
    @Value("${externalMenuList}")
    private String externalMenuList;
    @Value("${externalMenu}")
    private String externalMenu;
    @Override
    public MenuListVo getMenuList() {
        MenuListVo menuListVo = new MenuListVo();
        menuListVo.setGoogleAnalyticsAccount(googleAnalyticsAccount);
        List<Menu> menus = menuMapper.listMenu();
        if (menus == null) {
            return menuListVo;
        }
        int menuLen = menuMapper.getMenuLen();
        int menuCount = menus.size();
        if (menuCount <= menuLen) {
            menuListVo.setNormalList(menus);
        } else {
            menuListVo.setNormalList(menus.subList(0, menuLen));
            menuListVo.setMoreList(menus.subList(menuLen, menuCount));
        }
        return menuListVo;
    }

    @Override
    public MenuListVo getMenuInfoList(String userId, String role) throws IOException {
        MenuListVo menuListVo = new MenuListVo();
        List<MenuBarVo> menuBarVoList= menuBarMapper.listMenuByUserRol(role);
//        logger.error("==getMenuInfoList===userId=="+userId+"===role=="+role);
//        logger.error("==getMenuInfoList===menuBarVoList=="+ com.alibaba.fastjson.JSONObject.toJSONString(menuBarVoList));

        if (menuBarVoList == null) {
            return menuListVo;
        }
        List<String> featureVoList =featureMapper.listFeatureByUserId(userId);
        List<Menu> menuList = menuBarVoToMenu(menuBarVoList,featureVoList,role);

        // sort by orderNo
        if (!CollectionUtils.isEmpty(menuList)) {
            menuList.sort(Comparator.comparingInt(Menu::getOrderNo));
        }

        int menuCount = menuList.size();
        if (menuCount <= menuLens) {
            menuListVo.setNormalList(menuList);
        } else {
            menuListVo.setNormalList(menuList.subList(0, menuLens));
            menuListVo.setMoreList(menuList.subList(menuLens, menuCount));
        }
        menuListVo.setGoogleAnalyticsAccount(googleAnalyticsAccount);
        return menuListVo;
    }

    /**
     *
     * @param userId  userId
     * @param role role
     * @param pageMark pageMark
     * @return Menu
     * @throws Exception 编译异常
     */
    public Menu getUserPageMarkPermission(String userId, String role,String pageMark) throws Exception {
        boolean pageMarkFlag= false;

        List<MenuBarVo> menuBarVoList = menuBarMapper.listMenuByUserRol(role);
        if (menuBarVoList == null) {
            return null;
        }
        List<String> featureVoList = featureMapper.listFeatureByUserId(userId);
        Menu menu = new Menu();
        for (MenuBarVo menuBarVo : menuBarVoList) {
            if(!pageMark.equals(menuBarVo.getDataMark())){
                continue;
            }

            if (featureVoList.contains(menuBarVo.getFeatureId()) && menuBarVo.getAutoOwn() == 0) {
                menu.setPermission(true);
            } else if (menuBarVo.getAutoOwn() == 1) {
                menu.setPermission(true);
            } else {
                menu.setPermission(false);
            }
            pageMarkFlag=true;
        }
        if (!pageMarkFlag) {
            if ("true".equals(externalMenu)) {
                JSONArray jsonObjectexternalMenuList = new JSONArray(externalMenuList);
                if (jsonObjectexternalMenuList != null) {
                    for (int i = 0; i < jsonObjectexternalMenuList.length(); i++) {
                        JSONObject objectExternalMenu = new JSONObject(jsonObjectexternalMenuList.get(i).toString());
                        if (objectExternalMenu.get("permission").toString().contains(role)) {
                            menu.setPermission(true);
                        }
                    }
                }
            }
        }
        return menu;
    }
    /**
     * MenuBarVO to menu
     * @param list list
     * @param  featureVoList featureVoList
     * @param  role role
     * @return List
     */
    public List<Menu> menuBarVoToMenu(List<MenuBarVo> list, List<String> featureVoList,String role) {
        List<Menu> menuList = new ArrayList<Menu>();
        if (list == null || list.size() == 0) {
            return menuList;
        }
        JSONObject jsonObject = null;
        JSONArray jsonObjectexternalMenuList = null;
//        logger.error("=====menuBarVoToMenu======size==" + list.size());

        try {
            jsonObject = new JSONObject(menuMarkUrl);
            jsonObjectexternalMenuList = new JSONArray(externalMenuList);
            for (MenuBarVo menuBarVo : list) {
                try {
                    Menu menu = new Menu();
                    menu.setEnName(menuBarVo.getEnName());
                    menu.setChnName(menuBarVo.getCnName());
                    menu.setDataMark(menuBarVo.getDataMark());
                    menu.setOrderNo(menuBarVo.getOrderNo());
                    menu.setType(menuBarVo.getType());
                    menu.setStatus(menuBarVo.getEnable());
                    if (jsonObject != null) {

                        menu.setRedirectUrl(jsonObject.get(menuBarVo.getDataMark()).toString()) ;
                    }
                    if (featureVoList.contains(menuBarVo.getFeatureId()) && menuBarVo.getAutoOwn() == 0) {
                        menu.setPermission(true);
                    } else if (menuBarVo.getAutoOwn() == 1) {
                        menu.setPermission(true);
                    } else {
                        menu.setPermission(false);
                    }
                    // TODO add的时候需要去判断这个menu是否已经被添加到menuList中去，如果已经加上，会导致重复添加  lebron
                    menuList.add(menu);
                } catch (JSONException e) {
                    LOGGER.error("====JSONObject(jsonObject) Exception===" + e.getMessage());
                }
            }
            //添加额外菜单，需要前端配置对应的dataMark
            if("true".equals(externalMenu)){
                if(jsonObjectexternalMenuList !=null){
                    for (int i = 0; i <jsonObjectexternalMenuList.length() ; i++) {
                        try {
                            JSONObject objectExternalMenu = new JSONObject(jsonObjectexternalMenuList.get(i).toString());
                            if (objectExternalMenu.get("permission").toString().contains(role)) {
                                Menu menu = new Menu();
                                menu.setEnName(objectExternalMenu.get("enName").toString());
                                menu.setChnName(objectExternalMenu.get("chnName").toString());
                                menu.setDataMark(objectExternalMenu.get("dataMark").toString());
                                menu.setOrderNo(Integer.parseInt(objectExternalMenu.get("oderNo").toString()));
                                menu.setType(Integer.parseInt(objectExternalMenu.get("type").toString()));
                                menu.setStatus(Integer.parseInt(objectExternalMenu.get("status").toString()));
                                menu.setPermission(true);
                                menu.setRedirectUrl(objectExternalMenu.get("redirectUrl").toString());
                                menuList.add(menu);
                            }
                        } catch (JSONException e) {
                            LOGGER.error("====JSONObject(jsonObjectexternalMenuList) Exception===" + e.getMessage());
                        } catch (NumberFormatException e) {

                            LOGGER.error("====JSONObject(NumberFormatException) Exception===" + e.getMessage());
                        }
                    }
                }
            }
        } catch (JSONException e) {
            LOGGER.error("====JSONObject(menuMarkUrl) Exception===" + e.getMessage());
        }

//        logger.error("=====menuBarVoToMenu=menuList==size="+menuList.size());
        return menuList;
    }
}
